package com.example.agrigreennewssys.lucene;


import com.example.agrigreennewssys.dto.ArticleDetailDTO;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author 光的代言人
 */
@Service
public class LuceneIndexService {

    @Value("${spring.lucene.index-dir}")
    private String indexDir;

    // 构建索引
    public void createIndex(List<ArticleDetailDTO> detailDTOS) throws IOException {
        try (Directory directory = FSDirectory.open(Paths.get(indexDir));
             Analyzer analyzer = new SmartChineseAnalyzer();
             IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(analyzer))) {

            writer.deleteAll(); // 清空旧索引

            for (ArticleDetailDTO detailDTO : detailDTOS) {
                Document doc = buildDocument(detailDTO);
                writer.addDocument(doc);
            }
            writer.commit();
        }
    }

    //  构建单个文档
    private Document buildDocument(ArticleDetailDTO homeArticle) {
        Document doc = new Document();

        String content = homeArticle.getContent() != null ? homeArticle.getContent() : "";
        // 文章核心字段
        doc.add(new StringField("articleId", homeArticle.getArticleId().toString(), Field.Store.YES));
        doc.add(new TextField("title", homeArticle.getTitle(), Field.Store.YES));
        doc.add(new TextField("content", content, Field.Store.YES));
        // 用户信息
        doc.add(new StringField("nickName", homeArticle.getNickName(), Field.Store.YES));
        // 标签信息（存储为逗号分隔字符串）

        doc.add(new TextField("tagName", homeArticle.getTagName(), Field.Store.YES));
        // 其他业务字段
        doc.add(new StringField("avatarUrl", homeArticle.getAvatarUrl(), Field.Store.YES));
        doc.add(new StringField("createdAt",homeArticle.getCreatedAt(),Field.Store.YES));
        return doc;
    }

    // 新增方法：添加单个文档
    public void addArticleIndex(ArticleDetailDTO homeArticle) throws IOException {
        try (Directory directory = FSDirectory.open(Paths.get(indexDir));
             Analyzer analyzer = new SmartChineseAnalyzer();
             IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(analyzer).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND))) {

            Document doc = buildDocument(homeArticle);
            writer.addDocument(doc); // 使用 addDocument 而非 updateDocument
            writer.commit();
        }
    }

    //  更新索引
    public void updateArticleIndex(ArticleDetailDTO homeArticle) throws IOException {
        try (Directory directory = FSDirectory.open(Paths.get(indexDir));
             Analyzer analyzer = new SmartChineseAnalyzer();
             IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(analyzer).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND))) {
            Document doc = buildDocument(homeArticle);
            writer.updateDocument(new Term("articleId", homeArticle.getArticleId().toString()), doc);
            writer.commit();
        }
    }

    // 删除索引
    public void deleteArticleIndex(String articleId) throws IOException {
        try (Directory directory = FSDirectory.open(Paths.get(indexDir));
             IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(new SmartChineseAnalyzer()))) {

            writer.deleteDocuments(new Term("articleId", articleId));
            writer.commit();
        }
    }
}